import { defineStore } from "pinia";
import { monitorHistoryOptions } from "@/utils/common";
import { Names } from "../../store-namespace";
import { _get, _post, _put, _delete, http } from "@/utils/axios";
import { adminApis } from "@/api/backend/index";
import { EquipMonitor } from "@/api/backend/index";
import { splitEventList } from "@/utils/common";
import qs from "qs";
import { useWarnLog } from "@/store/backend/EquipM/warn";

interface Monitor {
  code: number;
  data: RootObject;
  msg: string;
}
interface RootObject {
  createBy: string | null;
  createTime: string | null;
  current: string | null;
  eid: number;
  id: number;
  ename: string | null;
  flow: string | null;
  hz: string | null;
  pa: string | null;
  params: anyObj;
  remark: string | null;
  runningTime: string | null;
  searchValue: string | null;
  temperature: string | null;
  updateBy: string | null;
  updateTime: string | null;
  voltage: string | null;
}
type S = {
  days: string[];
  times: number[];
};
type Calendar = {
  cellSize: number[];
  range: string[] | string;
};
// 后台实时设备监控
export const useBackendMonitor = defineStore(Names.BackendMonitor, {
  state: () => {
    return {
      pageSize: 10,
      pageNum: 1,
      loading: true, //默认为false
      status: 0, //设备状态
      calendar: {
        orient: "horizontal",
        cellSize: [22, 32],
        range: "2023",
        visualMapShow: true,
        year: "",
        mounth: "",
      }, //热力图基础配置
      // 单个设备数据
      itemData: {
        createBy: "",
        createTime: "",
        current: "",
        eid: 0,
        id: 0,
        ename: "",
        flow: "",
        hz: "",
        pa: "",
        params: {},
        remark: "",
        runningTime: "",
        searchValue: "",
        temperature: "",
        updateBy: "",
        updateTime: "",
        voltage: "",
      },
      // 单个设备基础信息
      deviceData: {
        addr: "",
        area: "",
        cTime: "",
        cardnumber: "",
        province: "",
        city: "",
        street: "",
        cname: "",
        estate: 0,
        gatewaycode: "",
        hearttime: 0,
        code: "",
        coordinate: {},
        createBy: null,
        createTime: null,
        describ: null,
        id: 13,
        institution: "",
        model: "",
        name: "",
        openState: 0,
        params: {},
        process: "",
        power: null,
        productName: "",
        recoveryDate: "",
        remark: "",
        replaceTime: "",
        searchValue: null,
        state: 0,
        updateBy: null,
        updateTime: null,
        user: "",
        userPhone: "",
        validity: null,
      },
      //单个设备历史数据
      deviceHis: [],
      //单个设备数据 监控模块
      tableData: [
        {
          icon: "el-icon-WindPower",
          parameter: "风速流量",
          current_value: "flow",
          type: "flow",
        },
        {
          icon: "fa fa-thermometer-3",
          parameter: "温度",
          current_value: "temperature",
          type: "temperature",
        },
        {
          icon: "el-icon-Odometer",
          parameter: "压强",
          current_value: "pa",
          type: "pa",
        },
        {
          icon: "fa fa-flash",
          parameter: "电流",
          current_value: "current",
          type: "current",
        },
        {
          icon: "fa fa-flash",
          parameter: "电频",
          current_value: "hz",
          type: "hz",
        },
        {
          icon: "fa fa-flash",
          parameter: "电压",
          current_value: "voltage",
          type: "voltage",
        },
        {
          icon: "fa fa-line-chart",
          parameter: "换炭以后环保设备运行时长",
          current_value: "thisTime",
          type: "thisTime",
        },
        {
          icon: "fa fa-line-chart",
          parameter: "环保设备总运行时长",
          current_value: "runningTime",
          type: "runningTime",
        },
      ],
      eventData: [
        {
          icon: "SwitchButton",
          eventType: "on",
          value: "开机",
          time: "2022-10-12",
        },
        {
          icon: "SwitchButton",
          eventType: "off",
          value: "关机",
          time: "2022-10-12",
        },
        {
          icon: "SwitchButton",
          eventType: "on",
          value: "开机",
          time: "2022-10-15",
        },
        {
          icon: "SwitchButton",
          eventType: "on",
          value: "开机",
          time: "2022-10-13",
        },
      ],
      userDataPc: [
        {
          name: "测试",
          createTime: "2012-10-03",
          enable: false,
          id: 0,
          telephone: 15778455589,
        },
        {
          name: "测试",
          createTime: "2012-10-03",
          enable: true,
          id: 1,
          telephone: 15778455589,
        },
        {
          name: "测试",
          createTime: "2012-10-03",
          enable: false,
          id: 2,
          telephone: 15778455589,
        },
        {
          name: "测试",
          createTime: "2012-10-03",
          enable: false,
          id: 3,
          telephone: 15778455589,
        },
      ],
      userDataMoblie: [
        {
          name: "1号",
          createTime: "2012-10-03",
          enable: false,
          id: 0,
          telephone: 15778455589,
        },
        {
          name: "1号",
          createTime: "2020-10-03",
          enable: true,
          id: 1,
          telephone: 15778455589,
        },
        {
          name: "5号",
          createTime: "2019-10-03",
          enable: false,
          id: 2,
          telephone: 15778455589,
        },
        {
          name: "7号",
          createTime: "2012-10-03",
          enable: false,
          id: 3,
          telephone: 15778455589,
        },
      ],
      Option: {
        color: ["#5470c6"],
        title: {
          text: "列表",
        },
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: [""],
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: "none",
            },
            dataView: { readOnly: false },
            restore: {},
            saveAsImage: {},
          },
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
        },
        yAxis: {
          type: "value",
          boundaryGap: [0, "100%"],
        },
        dataZoom: [
          {
            type: "inside",
            start: 0,
            end: 10,
          },
          {
            start: 0,
            end: 10,
          },
        ],
        series: [
          {
            name: "",
            type: "line",
            stack: "Total",
            data: [120, 132, 101, 134, 90, 230, 210],
          },
        ],
      }, //温度图表默认参数
      // Option: {}, //风速图表默认参数
      // OptionPa: {}, //压强图表默认参数
      countOption: {},
      //开机事件
      on: <any>[],
      //关机事件
      off: <any>[],
      //告警事件
      warn: <any>[],
      //更换滤芯事件
      change: <any>[],
      eventDone: false,
      historyFilter: <any>{},
    };
  },
  getters: {},
  actions: {
    //从后台获取该设备数据
    getDeviceMonitorData(id: number) {
      return new Promise((resolve, reject) => {});
    },
    changeChartOption(type: string, query: anyObj) {
      return new Promise((resolve, reject) => {
        switch (type) {
          case "flow":
            this.getNowListObject(query, type).then((res: any) => {
              if (res[0].length == 0) {
                this.Option.title.text = "暂无数据";
              } else {
                this.Option.title.text = "列表";
              }
              this.Option.legend.data = ["风速"];
              this.Option.series[0].name = "风速";
              this.Option.color = ["#91cc75"];
              this.Option.xAxis.data = res[1];
              this.Option.series[0].data = res[0] as number[];
              resolve("");
            });
            break;
          case "temperature":
            //获取的后台数据
            this.getNowListObject(query, type).then((res: any) => {
              if (res[0].length == 0) {
                this.Option.title.text = "暂无数据";
              } else {
                this.Option.title.text = "列表";
              }
              this.Option.legend.data = ["温度"];
              this.Option.series[0].name = "温度";
              this.Option.color = ["#ee6666"];
              this.Option.xAxis.data = res[1];
              this.Option.series[0].data = res[0] as number[];
              resolve("");
            });
            break;
          case "runningTime":
            this.getNowListObjectCalendar(query, type).then((res: any) => {
              resolve(res);
            });
            break;
          case "current":
            this.getNowListObject(query, type).then((res: any) => {
              if (res[0].length == 0) {
                this.Option.title.text = "暂无数据";
              } else {
                this.Option.title.text = "列表";
              }
              this.Option.legend.data = ["电流"];
              this.Option.series[0].name = "电流";
              this.Option.color = ["orange"];
              this.Option.xAxis.data = res[1];
              this.Option.series[0].data = res[0] as number[];
              resolve("");
            });
            break;
          case "hz":
            this.getNowListObject(query, type).then((res: any) => {
              if (res[0].length == 0) {
                this.Option.title.text = "暂无数据";
              } else {
                this.Option.title.text = "列表";
              }
              this.Option.legend.data = ["电频"];
              this.Option.series[0].name = "电频";
              this.Option.color = ["purple"];
              this.Option.xAxis.data = res[1];
              this.Option.series[0].data = res[0] as number[];
              resolve("");
            });
            break;
          case "voltage":
            this.getNowListObject(query, type).then((res: any) => {
              if (res[0].length == 0) {
                this.Option.title.text = "暂无数据";
              } else {
                this.Option.title.text = "列表";
              }
              this.Option.legend.data = ["电压"];
              this.Option.series[0].name = "电压";
              this.Option.color = ["black"];
              this.Option.xAxis.data = res[1];
              this.Option.series[0].data = res[0] as number[];
              resolve("");
            });
            break;
          default:
            this.getNowListObject(query, type).then((res: any) => {
              if (res[0].length == 0) {
                this.Option.title.text = "暂无数据";
              } else {
                this.Option.title.text = "列表";
              }
              this.Option.legend.data = ["压强"];
              this.Option.series[0].name = "压强";
              this.Option.color = ["#5470c6"];
              this.Option.xAxis.data = res[1];
              this.Option.series[0].data = res[0] as number[];
              resolve("");
            });
            break;
        }
      });
    },
    //查询单个设备监控实时数据
    getnowList(data: anyObj) {
      return new Promise((resolve, reject) => {
        _get(EquipMonitor + "/nowlist", data, "json", "")
          .then((res: any) => {
            this.itemData = res.data;
            resolve(res);
            console.log(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    },
    //轮询查询单个设备监控实时数据
    reSatrtGetnowList(data: anyObj) {
      return _get(EquipMonitor + "/nowlist", data, "json", "")
        .then((res: any) => {
          this.itemData = res.data;
          return res;
        })
        .catch((err) => {
          console.log(err);
          return err;
        });
    },
    //查询单个设备（复杂对象）
    getNowListObject(data: anyObj, type: string) {
      console.log("查询单个设备（复杂对象）", data);
      return new Promise((resolve, reject) => {
        _get(
          EquipMonitor +
            "/listbyhours?" +
            qs.stringify(data, { arrayFormat: "indices" }),
          { pageSize: 8640 },
          "json",
          ""
        ).then((res: any) => {
          console.log("resT", res, res.rows.length);
          let dataArray = monitorHistoryOptions(
            res.rows.length >= 1 ? [...res.rows] : [],
            type
          );
          resolve(dataArray);
        });
      });
    },
    //日历图单独获取数据
    getNowListObjectCalendar(data: anyObj, type: string) {
      console.log("日历图单独获取数据", data);
      return new Promise((resolve, reject) => {
        _get(
          EquipMonitor +
            "/listbyhours2?" +
            qs.stringify(data, { arrayFormat: "indices" }),
          { pageSize: 8460 },
          "json",
          ""
        ).then((res: any) => {
          console.log("resT", res, res.rows.length);
          let dataArray = monitorHistoryOptions(
            res.rows.length >= 1 ? [...res.rows] : [],
            type
          );
          resolve(dataArray);
        });
      });
    },
    //处理设备事件
    handleDevicesEvent(data: anyObj) {
      console.log("处理设备事件", data);
      const promises = data.map((item: any) => {
        switch (item.event) {
          case "开机":
            this.on.push(splitEventList(item.eventTime));
            return this.on;
          case "关机":
            this.off.push(splitEventList(item.eventTime));
            return this.off;
          // case "告警":
          //   this.warn.push(splitEventList(item.eventTime));
          //   return this.warn;
          default:
            this.change.push(splitEventList(item.eventTime));
            return this.change;
        }
      });
      Promise.all(promises).then(() => {
        this.eventDone = true;
        console.log("事件概览", this.on, this.off, this.change, this.warn);
      });
    },
    // );
    // },
    //历史数据
    getHistoryPage(data: anyObj) {
      return new Promise((resolve, reject) => {
        _get(
          EquipMonitor +
            "/list?" +
            qs.stringify({ eid: data.eid }, { arrayFormat: "indices" }),
          { pageSize: this.pageSize, pageNum: this.pageNum, eid: data.eid },
          "json",
          ""
        ).then((res: any) => {
          console.log("历史数据", res);
          resolve(res);
        });
      });
    },
    getHistoryPageMore(data: anyObj) {
      let pageObj = { pageSize: this.pageSize, pageNum: this.pageNum };
      console.log("data历史数据", {
        ...data,
      });
      this.historyFilter = {
        ...data,
        ...pageObj,
      };
      for (const key in data) {
        if (key === "createTime") {
          delete data.createTime;
        }
      }
      console.log("data历史数据", data);

      return new Promise((resolve, reject) => {
        _get(
          EquipMonitor +
            "/list?" +
            qs.stringify(data, { arrayFormat: "indices" }),
          {},
          "json",
          ""
        ).then((res: any) => {
          console.log("历史数据", res);
          resolve(res);
        });
      });
    },
    //重写获取实时数据
    getList(filter: any = {}) {
      return _get("/system/eqattribute/nowlistbylist", filter, "json", "")
        .then((res: any) => {
          console.log("重写获取实时数据", res);
          return res;
        })
        .catch((err) => {
          console.log(err);
          return err;
        });
    },
    //活性炭获取实时压力
    getNowListObjectForCarbon(data: anyObj, type: string) {
      return new Promise((resolve, reject) => {
        _get(
          EquipMonitor +
            "/listbyhours?" +
            qs.stringify(data, { arrayFormat: "indices" }),
          {},
          "json",
          ""
        ).then((res: any) => {
          resolve(res);
        });
      });
    },
    //历史数据排序
    getSortData(filter: any) {
      this.historyFilter = filter; //更新过滤
      for (const key in filter) {
        if (key === "createTime") {
          delete filter.createTime;
        }
      }
      return new Promise((resolve, reject) => {
        _get(
          EquipMonitor +
            "/list?" +
            qs.stringify(filter, { arrayFormat: "indices" }),
          {},
          "json",
          ""
        ).then((res: any) => {
          resolve(res);
        });
      });
    },
  },
});
